<?php

namespace App\Http\Controllers\TK_Api;

use App\Http\Requests\TK\FeedbackRequest;
use App\Http\Requests\TK\UploadRequest;
use App\Models\Config;
use App\Models\Feedback;
use App\Models\UserRank;
use App\Service\Aliyun\OssService;
use App\Service\Common\UploadService;
use Carbon\Carbon;
use DB;
use Exception;
use Faker\Provider\Uuid;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;

class CommonController extends ApiBaseController
{

    /**
     * 获取排名
     * @return JsonResponse|object
     */
    public function getRank() {
        $isPost = filter_var(request()->input('isPost'), FILTER_VALIDATE_BOOLEAN);
        if ($isPost) {
            $list = DB::table('tiku_user_knowledge_post')
                ->join('tiku_knowledge_post', 'tiku_user_knowledge_post.postId', '=', 'tiku_knowledge_post.id')
                ->select(DB::raw('tiku_knowledge_post.id, tiku_knowledge_post.title, count(postId) as count'))
                ->groupBy('postId')
                ->orderByDesc('count')
                ->limit(30)
                ->get();
        }else {
            $list = UserRank::orderByDesc('tiku_user_rank.count')
                ->join('user', 'tiku_user_rank.userId',  '=', 'user.id')
                ->select(['tiku_user_rank.id', 'user.nickname', 'user.username', 'user.avatar', 'tiku_user_rank.count'])
                ->limit(30)
                ->get();
        }

        return $this->restful($list);
    }

    /**
     * 意见反馈
     * @param FeedbackRequest $request
     * @return JsonResponse|object
     */
    public function feedbackStore(FeedbackRequest $request) {
        $params = $request->validated();
        $userId = $this->user->id;
        $params['userId'] = $userId;
        $params['createdAt'] = time();

        $feedback = Feedback::create($params);

        return $this->restful($feedback);
    }

    /**
     * 获取初始化信息
     * @return JsonResponse|object
     */
    public function init() {
        $notice = Config::where('name', 'mp_notice')->value('value') ?? '';
        $about = Config::where('name', 'mp_about')->value('value') ?? '';
        return $this->restful(compact('notice', 'about'));
    }

    /**
     * 上传文件
     * @param UploadRequest $request
     * @param OssService $ossService
     * @return JsonResponse|object
     * @throws Exception
     */
    public function uploadFile(UploadRequest $request, UploadService $service) {
        // return $this->restful(null, false, '上次通道暂未开放');
        //
        $params = $request->validated();
        // $file = $params['file'];
        // $url = $ossService->upload($file);
        //
        // return $this->restful($url);

        $file = $service->uploadToFtp($params);
        return $this->restful($file);
    }
    public function uploadFile2(OssService $ossService) {
        $filePath = request('filePath');
        if (empty($filePath)) return $this->restful(null, false, '请稍后再试');

        $localPath = onlineFileToDiskFile($filePath);
        if (!$localPath) return $this->restful(null, false, '请稍后再试');

        try {
            $url = $ossService->moveToOss($localPath, '/uploads/' . Carbon::now()->format('Ymd') . '/', generateRandomString() . time() . '.' . pathinfo($filePath, PATHINFO_EXTENSION));
        } catch (Exception $e) {
            return $this->restful(null, false, '请稍后再试');
        }

        return $this->restful($url);
    }
}
